/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.arguscab.game;

import hu.arguscab.ai.game.Bot;
import hu.arguscab.physic.Vector;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

/**
 *
 * @author sharp
 */
public class GameScene extends Scene {
	public final static int WIDTH = 1024;
	public final static int HEIGHT = 768;
	private final Logger log = LoggerFactory.getLogger(GameScene.class);

	private List<Ship> ships = new ArrayList<Ship>();
	private Ship target;
	public static Map map;
	
	
	@Override
	protected boolean isActive() {
		return Display.isActive();
	}

	@Override
	protected boolean isCloseRequested() {
		return Display.isCloseRequested();
	}

	@Override
	public boolean init() throws Exception {
		log.info("Init TestScene");

		Display.setTitle("TestScene");
		Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
		try {
			Display.setFullscreen(false);
		} catch (LWJGLException ex) {}
		Display.setVSyncEnabled(false);
		Display.create();

		glDisable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0, WIDTH, HEIGHT, 0, -1, 1);
		// Game
		GameInfo.instance().Init(WIDTH, HEIGHT);

		target = new Ship(null, null);

		GUI.init(this);
		
		map = new Map();
		map.generate();
		return true;
	}

	@Override
	public void deInit() {
		Display.destroy();
	}

	@Override
	synchronized protected void logic() {
		if ( isActive() ) {
			for (Ship s : ships) {
				s.update();
			}
		}
	}

	@Override
	synchronized protected void render() {
		glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
		for (Ship s : ships) {
			s.draw();
		}
		target.draw();
		map.draw();
		
		Display.update();
		Display.setTitle("Performance: " + getPerfomance() + "%");
	}

	@Override
	synchronized protected void click(int x, int y, int btn) {
		y = HEIGHT - y;
		Ship t = null;
		if (btn == 0) {
			target.getState().setPos(new Vector(x, y));
			t = target;
		}
		for (Ship s : ships) {
			Bot bot = (Bot) s.getController();
			bot.setTarget(t);
		}
	}


	@Required
	synchronized public void setShips(List<Ship> ship) {
		this.ships = ship;
		for (Ship s : ships) {
			s.getState().setPos(new Vector(	Math.random()*WIDTH,
											Math.random()*HEIGHT) );
		}
	}

	synchronized public void addShip(Ship s) {
		ships.add(s);
	}

	synchronized public void delShip(Ship s) {
		ships.remove(s);
	}

}
